C++ union 与 reinterpret_cast
全部标签 我有一个这样声明的union:union{intall[4];struct{inta,b,c,d;};};点allarray只是为了简化4个字段的迭代。为了让它更简单,我想用std::array替换它.那会使我暴露于nasaldemons吗?? 最佳答案 首先,重要的是要注意,union中只有两个不同类型的对象永远不会是未定义的。未定义的是写入一个并从另一个读取,但有一个异常(exception):[C++11:9.5/1]:[Note:Onespecialguaranteeismadeinordertosimplifytheuse
我正在调整一些C++03代码以利用C++11的新可能性,特别是以C++11的方式引入移动语义。但是我遇到了一个struct,这让我很头疼,因为它包含一个匿名union。它具有全局形式structtree{//dataof|tree|enum{tag0,tag1,tag2,...}kind;union{type1field1;type2field2;...};//constructorstree():kind(tag0){}//default,emptystatetree(const&type1x):kind(tag1),field1(x){}//variant1tree(const&t
当我们执行以下操作时实际发生了什么:1)inti=-1;//32bitvoid*p;p=reinterpret_cast(i)在64位架构上,sizeof(void*)==82)longlongi;//64bitvoid*p=(unsignedint)(-1);i=retinterpret_cast(p)在32位架构上sizeof(void*)=4我大体上知道结果是什么,但我希望有人用C++标准来描述这个机制,以便更好地理解。在第二种情况下,行为类似于“积分促销”(4.5)中描述的行为(我将为-1)对于“int-unsignedlong”的情况,我们通常会说指针像有符号整数一样转换吗?
这个问题在这里已经有了答案:Downcastingusingthe'static_cast'inC++(3个答案)关闭8年前。我不明白为什么会这样。pReallyABase是一个向下转换的shared_pointer,它指向一个基类实例。我理解为什么编译器让我调用pReallyABase->onlyForDerived()因为我将它定义为派生类指针,但是当我尝试使用该指针调用派生类函数时为什么没有出现运行时错误?classBase{public:virtualstringwhatAmI(){return"IamaBase";}};classDerived:publicBase{publ
触发union的非事件成员的左值到右值转换不是常量表达式。也就是说,给定union:templateunionA{constexprA(Tt):t_{t}{}constexprA(Uu):u_{u}{}Tt_;Uu_;};和constexpr函数foo:templateconstexprautofoo(){Aa(T{});returna.u_;}以下程序:intmain(){constexprautotest=foo();return0;}失败并显示错误消息:error:constexprvariable'test'mustbeinitializedbyaconstantexpress
玩constexpr和union我发现,我无法更改union的活跃成员在constexpr.只有一个异常(exception):union空类。constexprboolt(){structA{};structB{};unionU{Aa;Bb;}u{};u.a=A{};u.b=B{};returntrue;}static_assert(t());constexprboolf(){structA{charc;};structB{charc;};unionU{Aa;Bb;}u{};u.a=A{};u.b=B{};//errororiginatingfromherereturntrue;}s
我正在编写与对齐相关的代码,如果给定的指针正确对齐,却没有标准的功能测试,这让我感到非常惊讶。似乎互联网上的大多数代码都使用(long)ptr或reinterpret_cast(ptr)测试对齐,我也使用了它们,但我想知道使用指向整数类型的强制转换指针是否符合标准。这里是否有任何系统触发断言?charch[2];assert(reinterpret_cast(reinterpret_cast(&ch[0])+1)==&ch[1]); 最佳答案 回答题目中的问题:没有。反例:在旧的Pr1me微型计算机上,一个普通指针是两个16位字。第
考虑以下代码#include#include#include#includestructBase{intx;Base(intx):x(x){}};structDerived:publicBase{inty,z;Derived(intx):Base(x),y(x+1),z(x+2){}};voidupdate(conststd::vector>&elements){for(constautoelem:elements){std::coutx>elements(4);{intctr=0;std::generate(begin(elements),end(elements),[&ctr]()
我最近阅读了union体默认构造函数的描述:DefaultConstructor有如下规律:BlockquoteDeletedimplicitly-declareddefaultconstructor:[...]Tisaunionwithatleastonevariantmemberwithnon-trivialdefaultconstructor,andnovariantmemberofThasadefaultmemberinitializer.[...]然后我决定做一个练习来验证规则。structMember{public://Member():mX(0){}virtualintG
Paragraph4of[expr.cast](在撰写本文时可用的最新C++标准草案中)描述了C样式转换的行为如下:Theconversionsperformedbyaconst_cast,astatic_cast,astatic_castfollowedbyaconst_cast,areinterpret_cast,orareinterpret_castfollowedbyaconst_cast,canbeperformedusingthecastnotationofexplicittypeconversion.Thesamesemanticrestrictionsan